package com.adobe.apprise.commands
{
	import com.adobe.air.alert.NativeAlert;
	import com.adobe.apprise.events.AggregateEvent;
	import com.adobe.apprise.events.ImportFeedsEvent;
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import flash.filesystem.FileStream;
	import flash.filesystem.FileMode;
	import mx.collections.ArrayCollection;
	
	public class ImportFeedsCommand implements ICommand
	{
		public function execute(ce:CairngormEvent):void
		{
			var fs:FileStream = new FileStream();
            fs.open(ImportFeedsEvent(ce).feedFile, FileMode.READ);
            var opmlStr:String = fs.readUTFBytes(fs.bytesAvailable);
            fs.close();
            var opml:XML;
            try
            {
                opml = new XML(opmlStr);
            }
            catch (e:Error)
            {
				NativeAlert.show("Invalid XML File", "Parse Error", NativeAlert.OK, true);
                return;
            }
            var xmlUrls:ArrayCollection = new ArrayCollection();
            for each (var xmlUrl:String in opml..@xmlUrl)
            {
                if (!xmlUrls.contains(xmlUrl))
                {
                    xmlUrls.addItem(xmlUrl);
                }
            }
            
            if (xmlUrls.length == 0)
            {
				NativeAlert.show("Invalid OPML File", "Parse Error", NativeAlert.OK, true);
                return;
            }
            
            var age:AggregateEvent = new AggregateEvent();
            age.feeds = xmlUrls.source;
            age.dispatch();
		}
	}
}
